package com.app.config;

import com.app.entity.Jwtobject;
import io.jsonwebtoken.*;
import io.jsonwebtoken.impl.DefaultHeader;
import net.sf.json.JSONObject;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.util.Date;

public class JWTtoken {
    public static final String JWT_SECRET = "123456";//密钥
    public static final String JWT_HEADER_ALG = SignatureAlgorithm.HS256.getValue();
    public static final String JWT_HEADER_TYP = "JWT";
    public final static int EXPMILLIS_WEBBROWSER = 1000 * 60 * 60 * 24 * 7;//一周
    public final static int EXPMILLIS_ANDROIDAPP = 1000 * 60 * 60 * 24 * 365;//一年
    public static String getToken(String userid,String key,String starttime,String endtime,String extend)
    {
        Jwtobject obj = new Jwtobject();
        obj.setEndtime(endtime);
        obj.setExtend(extend);
        obj.setStarttime(starttime);
        obj.setKey(key);
        obj.setUserid(userid);
        JSONObject jsonObj = JSONObject.fromObject(obj);
        SignatureAlgorithm signtureAlgorithm = SignatureAlgorithm.HS256;
        Long startdate = Long.parseLong(starttime);
        Date now = new Date(startdate);
        Long enddate = Long.parseLong(endtime);
        Date exp = new Date(enddate);
        SecretKey signingKey = generalKey();
        Header header = new DefaultHeader();
        header.setCompressionAlgorithm(JWT_HEADER_ALG);
        header.setType(JWT_HEADER_TYP);
        JwtBuilder builder = Jwts.builder()
                .setHeaderParam(Header.TYPE,JWT_HEADER_TYP)
                .setIssuedAt(now)
                .setSubject(jsonObj.toString())
                .signWith(signtureAlgorithm,signingKey)
                .setExpiration(exp);
        return builder.compact();
    }

    public static String parseToken(String token)
    {
        SecretKey key = generalKey();
        Claims claims = Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(token).getBody();
        return claims.toString();
    }
    private  static SecretKey generalKey()
    {
        byte[] apikey = DatatypeConverter.parseBase64Binary(JWT_SECRET);
        return new SecretKeySpec(apikey,SignatureAlgorithm.HS256.getJcaName());
    }
}
